// 按钮防抖v-debounce:500(单位ms)
import type { Directive, DirectiveBinding } from "vue";
import { onUnmounted } from "vue";

export const debounce: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding<Function>) {
    const { value: fn, arg } = binding;
    let timer;
    const delay = arg || 300; // 默认延迟时间为300ms

    const debouncedFn = (...args) => {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        fn(...args);
      }, delay);
    };
    el.addEventListener("click", debouncedFn);

    onUnmounted(() => {
      clearTimeout(timer);
    });
  }
};
